#include <stdlib.h>
#include <stdio.h>
#include <SDL/SDL.h>
#include <SDL/SDL_image.h>
#include "SDL/SDL_ttf.h"
#include <SDL/SDL_mixer.h>

	
Uint32 bougerObjet(Uint32 intervalle, void *parametre);
SDL_TimerID SDL_AddTimer(Uint32 interval, SDL_NewTimerCallback callback, void *param);
int checkcollision (SDL_Rect pos1, SDL_Rect pos2);
//Uint32 bougerBoost(Uint32 intervalle, void *parametre);



int main(int argc, char *argv[])
{
/********declaration variables********/
SDL_Surface *ecran = NULL , *image = NULL, *bg[6] = {NULL} , *coin = NULL, *DK = NULL, *Obstacle = NULL, *GO = NULL, *b[3]= {NULL}, *B = NULL;
SDL_Rect positionImage, positioncoin, positionDK, positionObstacle, positionGO, posB;
SDL_Event event;
int continuer = 1,  money=0, x=0, w=0, j=0, q=0, k=0, i=0, loop=0;
SDL_Color color={255,255,255},  c1={255, 0, 255};

/***Timing variables***/
SDL_TimerID timer, timer2, timerB;
int tempsPrecedent = 0, tempsActuel = 0, time=0;
SDL_Surface *text=NULL, *text1=NULL, *temps=NULL, *temps1=NULL;
SDL_Rect Rectangle_Destination, Rec_t1, Rec_temps, Rec_te1 ;
char score[100],tmp[100];
/***Timing variables***/

/******fin declaration variables******/

/********** initialiser SDL **********/
SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER | SDL_INIT_AUDIO);
ecran = SDL_SetVideoMode(720, 500, 32, SDL_HWSURFACE|SDL_DOUBLEBUF);
SDL_WM_SetCaption("Stage3", NULL);

   if(TTF_Init() == -1)
    {
        fprintf(stderr, "Erreur d'initialisation de TTF_Init : %s\n", TTF_GetError());
        exit(EXIT_FAILURE);
    }


TTF_Font *font = NULL;

font= TTF_OpenFont("fonts/tuning_fork.ttf", 44);
if ( ! font)
{
fprintf(stderr, " Erreur : impossible de charger la police de caractères font.ttf ( tuning_fork) \n");
exit(2);
}


  
/**************fin init**************/

/********initialisation du bg********/

bg[0] = IMG_Load("Pic/map1.jpg");
bg[1] = IMG_Load("Pic/map2.jpg");
bg[2] = IMG_Load("Pic/map3.jpg");
bg[3] = IMG_Load("Pic/map4.jpg");
bg[4] = IMG_Load("Pic/map5.jpg");
bg[5] = IMG_Load("Pic/map6.jpg");
positionDK.x = 0;
positionDK.y = 0 ;
for (w=0; w<=5; w++)
{
if(bg[w] == NULL)    return EXIT_FAILURE;
SDL_SetColorKey(bg[w], SDL_SRCCOLORKEY,SDL_MapRGB(bg[w]->format,0,0,0));
}

DK = bg[0];

/*********fin initialisation*********/


/******initialisationde voiture******/
image = IMG_Load("Pic/car.png");
positionImage.x = 0 ;
positionImage.y = (ecran->w / 2) - (image->w / 2)   ;
SDL_SetColorKey(image, SDL_SRCCOLORKEY , SDL_MapRGB(image->format,0,0,0) );
if(image == NULL)    return EXIT_FAILURE;
/*********fin initialisation*********/

/****** initialisationde coin******/
coin = IMG_Load("Pic/money.jpg");
positioncoin.x = ((ecran->w / 2)- (coin->w / 2)) - 30;
positioncoin.y = 0;
SDL_SetColorKey(coin, SDL_SRCCOLORKEY,SDL_MapRGB(coin->format,255,255,255));

/*********fin initialisation*********/

/********initialisation des boost********/

b[0] = IMG_Load("Pic/boost1.jpg");
b[1] = IMG_Load("Pic/boost2.jpg");
b[2] = IMG_Load("Pic/boost3.jpg");
posB.x = 0;
posB.y = 0 ;
for (w=0; w<=2; w++)
{
if(b[w] == NULL)    return EXIT_FAILURE;
SDL_SetColorKey(b[w], SDL_SRCCOLORKEY,SDL_MapRGB(b[w]->format,255,255,255));
}
int o=0;
o = (rand() % 10)+ 5;
k = (rand() % 5 ) + 1;
B = b[k];
k=0;
timerB = SDL_AddTimer(o,bougerObjet, &posB);

/*********fin initialisation*********/

/****** initialisationde obstacle******/
Obstacle = IMG_Load("Pic/p1.jpg");
positionObstacle.x = 300;
positionObstacle.y = 0;
SDL_SetColorKey(Obstacle, SDL_SRCCOLORKEY, SDL_MapRGB(coin->format,255,255,255));
/*********fin initialisation*********/

/****** initialisationde GameOver******/
GO = IMG_Load("Pic/GO.jpg");
positionGO.x = 0;
positionGO.y = 0;
SDL_SetColorKey(GO, SDL_SRCCOLORKEY, SDL_MapRGB(GO->format,0,0,0));
/*********fin initialisation*********/


/****** Chargement musique******/
if(Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, MIX_DEFAULT_CHANNELS, 1024) == -1) //Initialisation de l'API Mixer
   {
      printf("%s", Mix_GetError());
   }
   Mix_Music *musique; //Création du pointeur de type Mix_Music
   musique = Mix_LoadMUS("Music/2-25-final-battle.mp3"); //Chargement de la musique
   loop= -1;
   Mix_PlayMusic(musique, loop); //-1= nbre de loop: Jouer infiniment la musique

/*********fin chargement*********/
int f=0;
tempsActuel = SDL_GetTicks();
time=tempsActuel/1000;
f=(rand() % 60 )+1 ;
if (time == f)
{
timer = 0;
}
else 
{
timer = SDL_AddTimer(10, bougerObjet, &positioncoin); //coin
}
timer2 = SDL_AddTimer(15, bougerObjet, &positionObstacle); //obs
SDL_EnableKeyRepeat(20,20); //appui continu
/*************Game loop*************/
while (continuer && ( time < 60  ))
{
SDL_PollEvent(&event);
switch(event.type)
{
        case SDL_QUIT:
        continuer = 0;
        break;

        case SDL_KEYDOWN:
         switch(event.key.keysym.sym)
                {
              case SDLK_RIGHT:
              if (positionImage.x < 420 )
                        {
                        positionImage.x+=10;
                        }
	            x= checkcollision(positionImage, positioncoin);
		   q=checkcollision(positionImage, positionObstacle);
		   i=checkcollision(positionImage, posB);
	    	  if (x == 1)
			{   
			    money= money+1 ;
			    x==0;
			positioncoin.x = 200;
			positioncoin.y = -30;
			
			}
		if ( (q == 0) && (positionObstacle.x == 500) )
		{
			positionObstacle.x = 300;
			positionObstacle.y = 0;
		}
		if ( q == 1 )
		{
		musique = Mix_LoadMUS("Music/Game_Over.mp3");
		SDL_BlitSurface(GO, NULL, ecran, &positionGO);
		SDL_Flip(ecran);
		SDL_Delay(1000);
		continuer =0;
		return EXIT_FAILURE;
		}
		/*if ( i == 1)
		{
		switch (k)
			{
			case k=1
			boost1;//fonction d'activation du premier boost
			break;
			case k=2
			boost2;//fonction d'activation du deuxieme boost
			break;
			case k=3
			boost3;//fonction d'activation du troisieme boost
			break;
			}		
		}*/
                        break;
              case SDLK_LEFT:
              if (positionImage.x > 155)
                        {                      
                        positionImage.x-=10;
                        }
		x= checkcollision(positionImage, positioncoin);
		q=checkcollision(positionImage, positionObstacle);
		if (x==1)
			{   
			money= money+1 ;
			x=0;
			positioncoin.x = 200;
			positioncoin.y = -30;
			
			}
		if ( (q == 0) && (positionObstacle.x == 500) )
		{
			positionObstacle.x = 300;
			positionObstacle.y = 0;
		}
		if ( q == 1 )
		{
		musique = Mix_LoadMUS("Music/Game_Over.mp3");
		SDL_BlitSurface(GO, NULL, ecran, &positionGO);
		SDL_Flip(ecran);
		SDL_Delay(1000);
		continuer =0;
		return EXIT_FAILURE;

		}
		/*if ( i == 1)
		{
		switch (k)
			{
			case k=1
			boost1;//fonction d'activation du premier boost
			break;
			case k=2
			boost2;//fonction d'activation du deuxieme boost
			break;
			case k=3
			boost3;//fonction d'activation du troisieme boost
			break;
			}		
		}*/
	         
                        break;
               } 
 }

/********affichage des images********/

/************Affichage BG************/
   if (tempsActuel - tempsPrecedent > 30)
   {
      if(j == 5){
          j = 0;
      }
      DK = bg[j++];
      tempsPrecedent = tempsActuel;
   }
SDL_BlitSurface(DK, NULL, ecran, &positionDK);

/************End Affichage************/


/************Affichage Score**********/
text1 = TTF_RenderText_Solid(font, "Score ", color);
Rec_t1.x = 0;
Rec_t1.y = 0;
SDL_BlitSurface(text1, NULL, ecran, &Rec_t1);
sprintf(score, "%d", money);
text = TTF_RenderText_Solid(font, score, c1);
Rectangle_Destination.x = 130;
Rectangle_Destination.y = 0;
SDL_BlitSurface(text, NULL, ecran, &Rectangle_Destination);
/************End Affichage************/

/************Affichage TEMPS *********/
temps = TTF_RenderText_Solid(font, "Temps ", color);
Rec_temps.x = 0;
Rec_temps.y = 60;
SDL_BlitSurface(temps, NULL, ecran, &Rec_temps);
sprintf(tmp, "%d", (tempsActuel/1000));
temps1 = TTF_RenderText_Solid(font, tmp, c1);
Rec_te1.x = 130;
Rec_te1.y = 60;
SDL_BlitSurface(temps1, NULL, ecran, &Rec_te1);
/************End Affichage************/


SDL_BlitSurface(image, NULL, ecran, &positionImage);
SDL_BlitSurface(coin, NULL, ecran, &positioncoin);
SDL_BlitSurface(Obstacle, NULL, ecran, &positionObstacle);
SDL_BlitSurface(B, NULL, ecran, &posB);

/***********fin affichage***********/

SDL_Flip(ecran);
}//End while

/**********End of Game loop**********/


/***********Free Memory************/
SDL_FreeSurface(image);
SDL_FreeSurface(coin);
SDL_FreeSurface(Obstacle);
SDL_FreeSurface(bg[1]);
SDL_FreeSurface(bg[2]);
SDL_FreeSurface(bg[3]);
SDL_FreeSurface(bg[4]);
SDL_FreeSurface(bg[5]);
SDL_FreeSurface(bg[6]);
SDL_FreeSurface(b[1]);
SDL_FreeSurface(b[2]);
SDL_FreeSurface(b[3]);
SDL_FreeSurface(temps);
SDL_FreeSurface(temps1);
SDL_FreeSurface(text);
SDL_FreeSurface(text1);
SDL_RemoveTimer(timer); /* Arrêt du timer */
SDL_RemoveTimer(timer2);
SDL_RemoveTimer(timerB);
TTF_Quit();
Mix_FreeMusic(musique);
Mix_CloseAudio();
Mix_Quit();
SDL_Quit();
/************End of Free************/

return EXIT_SUCCESS;
}

/* Fonction de callback (sera appelée toutes les 5 ms) */
Uint32 bougerObjet(Uint32 intervalle, void *parametre)
{
int aleatoire, a=1, tempsActuel=0, time=0 ;
tempsActuel = SDL_GetTicks();
time=tempsActuel/1000;

    SDL_Rect* positionObjet = parametre; /* Conversion de void* en SDL_Rect* */
    positionObjet->y++;
    aleatoire = rand();
	if ( (aleatoire % 2) == 0)
	{
	if (positionObjet->x > 250)
	{
	    positionObjet->x-=a;
		if ((time % 2) != 0)
	    {a+=1;}
	else if ((time % 2) == 0)
	    {a+=5;}
	}
	}
	else { 
	if (positionObjet->x < 350)
	{
	positionObjet->x+=a;

	}
	  }

    return intervalle;
}



int checkcollision (SDL_Rect pos1, SDL_Rect pos2)
{
int h=0;
 if (  ( (pos2.x < (pos1.x+123 )) && ( pos2.x > pos1.x ) )  && ( pos2.y > pos1.y) )
{ h=1; }
return h;
}
//Uint32 bougerBoost(Uint32 intervalle, void *parametre)
//{
//SDL_Rect* pos = parametre;
//return intervalle;
//}
